<template>
  <div id="webgl-container" class="webgl-container">
    <canvas id="webgl" class="webgl"/>
  </div>

  <MoreInfo>
    <p>只有 MeshBasicMaterial 不受光照的影响。</p>
    <p>shininess 设置决定了镜面高光的光泽度。它的默认值是30。</p>
    <p>
      roughness
      粗糙度高的东西，比如棒球，就不会有很强烈的反光，而不粗糙的东西，比如台球，就很有光泽
    </p>
    <p>
      metalness 材质的金属度。金属与非金属的表现不同。0代表非金属，1代表金属
    </p>
    <p>
      如果想从使用无纹理切换到使用纹理，或者从使用纹理切换到无纹理，那么需要设置
      needsUpdate = true。
    </p>
    <el-divider />
    <p>网址：</p>

    <el-link
      href="https://hdri-haven.com/"
      type="primary"
      target="_blank"
    >https://hdri-haven.com/</el-link
    >
    <el-link
      href="https://matheowis.github.io/HDRI-to-CubeMap/"
      type="primary"
      target="_blank"
    >https://matheowis.github.io/HDRI-to-CubeMap/</el-link
    >
    <el-link
      href="https://github.com/nidorx/matcaps"
      type="primary"
      target="_blank"
    >https://github.com/nidorx/matcaps</el-link
    >
  </MoreInfo>
</template>

<script setup>
import {
  AmbientLight,
  BoxGeometry,
  Mesh,
  MeshBasicMaterial,
  MeshLambertMaterial,
  MeshPhongMaterial
} from 'three'

import MoreInfo from '@/components/MoreInfo.vue'
import { useThree } from '@/hooks/use-three-hook'

const { gui, scene, camera, addAnimationCallback } = useThree()

let cube
const params = {
  type: 'MeshBasicMaterial',
  color: 0x00ff00
}

onMounted(() => {
  if (scene.value && camera.value) {
    const box = new BoxGeometry(1, 1, 1)
    const material = new MeshBasicMaterial({ color: 0x00ff00 })
    cube = new Mesh(box, material)
    scene.value.add(cube)
    const light = new AmbientLight(0x404040) // 柔和的白光
    scene.value.add(light)

    gui
      .add(params, 'type', [
        'MeshBasicMaterial',
        'MeshLambertMaterial',
        'MeshPhongMaterial'
      ])
      .name('材质类型')
      .onChange((v) => {
        if (Array.isArray(cube.material)) {
          cube.material.forEach((m) => {
            m.dispose()
          })
        } else {
          cube.material.dispose()
        }

        if (v === 'MeshBasicMaterial') {
          cube.material = new MeshBasicMaterial({ color: params.color })
        } else if (v === 'MeshLambertMaterial') {
          cube.material = new MeshLambertMaterial({ color: params.color })
        } else if (v === 'MeshPhongMaterial') {
          const material = new MeshPhongMaterial()
          material.color.set(params.color) // 红色
          material.flatShading = true
          material.shininess = 130 // 高光
          material.needsUpdate = true
          cube.material = material
        }
      })

    gui
      .add(params, 'color', {
        red: 0xff0000,
        green: 0x00ff00,
        blue: 0x0000ff
      })
      .name('颜色')
      .onChange((v) => {
        cube.material.color.set(v)
      })

    addAnimationCallback((delta) => {
      cube.rotation.x += delta
      cube.rotation.y += delta * 0.5
    })
  }
})
</script>
